<template>
  <div>
    <div class="database">
      <!-- {{ form }} -->
      <el-form ref="formRef" :model="form" label-width="100px" style="margin-top: 40px">
        <el-form-item label="数据库名称">
          <el-input v-model="form.name" readonly />
        </el-form-item>
        <el-form-item label="JDBC URL">
          <el-input v-model="form.url" readonly />
        </el-form-item>
        <el-form-item label="用户">
          <el-tag
            closable
            v-for="(item, index) in userList"
            :key="index"
            class="mx-1"
            @close="userClose(item)"
            @click="userClick(item)"
          >
            <span style="cursor: pointer">
              {{ item.name }}
            </span>
          </el-tag>
          <el-button type="primary" :icon="Plus" style="margin-left: 10px" size="small" @click="addUser">
            添加用户
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
  <el-dialog title="添加用户" :model-value="dialogVisible" width="30%" @close="addClose">
    <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="100px">
      <el-form-item label="用户名" prop="name">
        <el-input v-model="addForm.name" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="账号" prop="username">
        <el-input v-model="addForm.username" placeholder="请输入账号" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" show-password v-model="addForm.password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="标签" prop="tag">
        <el-tag
          v-for="tag in addForm.tag"
          :key="tag"
          @close="handleClose(tag)"
          class="mx-1"
          closable
          :disable-transitions="false"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="InputRef"
          v-model="inputValue"
          class="ml-1 w-20"
          size="small"
          style="width: 100px"
          @keyup.enter="handleInputConfirm"
          @blur="handleInputConfirm"
        />
        <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">新增标签</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="submitBtnLoading" @click="handleCreate">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from 'vue-demi'
import { Plus, Search, CircleClose } from '@element-plus/icons-vue'
import { addUserApi, userListApi, userDelApi, userInfoApi, updateUserApi } from '@/api/datasourceCenter'
import { ElMessage, ElMessageBox } from 'element-plus'
const props = defineProps({
  datasource: {
    type: Object,
    default: {},
    required: true
  },
  modifyKey: {
    type: String,
    default: '',
    required: true
  }
})
const addFormRef = ref(null)
const InputRef = ref(null)
const dialogVisible = ref(false)
const inputVisible = ref(false)
const submitBtnLoading = ref(false)
const inputValue = ref('')
const form = ref({})
const userList = ref([])
const addRules = reactive({
  name: [{ required: true, trigger: 'blur', message: '请输入用户名！' }],
  username: [{ required: true, trigger: 'blur', message: '请输入账号！' }],
  password: [{ required: true, trigger: 'blur', message: '请输入密码！' }]
})
const addForm = ref({
  name: '',
  username: '',
  password: '',
  tag: []
})
const addUser = () => {
  dialogVisible.value = true
}
const userClose = (item) => {
  ElMessageBox.confirm(`确定要删除此用户吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: '警告'
  }).then(() => {
    userDelApi(item._id).then(() => {
      ElMessage.success('删除成功')
      getUserList()
    })
  })
}
const userClick = (item) => {
  dialogVisible.value = true
  userInfoApi(item._id).then((res) => {
    Object.assign(addForm.value, res.data)
  })
}
const handleCreate = () => {
  addFormRef.value?.validate((valid) => {
    if (valid) {
      submitBtnLoading.value = true
      if (addForm.value._id) {
        updateUserApi(addForm.value)
          .then((res) => {
            ElMessage.success('修改成功')
            dialogVisible.value = false
            getUserList()
          })
          .finally(() => {
            submitBtnLoading.value = false
          })
      } else {
        let params = { ...addForm.value }
        params.dataSourceId = form.value._id
        console.log(params)
        addUserApi(params)
          .then((res) => {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            getUserList()
          })
          .finally(() => {
            submitBtnLoading.value = false
          })
      }
    } else {
      return false
    }
  })
}
const addClose = () => {
  addForm.value = {
    name: '',
    username: '',
    password: '',
    tag: []
  }
  addFormRef.value.resetFields()
  dialogVisible.value = false
}

const handleClose = (tag) => {
  addForm.value.tag.splice(addForm.value.tag.indexOf(tag), 1)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value.input.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    addForm.value.tag.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}
watch(
  () => props.datasource,
  () => {
    Object.assign(form.value, props.datasource[props.modifyKey])
  },
  {
    deep: true,
    immediate: true
  }
)
onMounted(() => {
  getUserList()
})
const getUserList = () => {
  userListApi({ dataSourceId: form.value._id }).then((res) => {
    userList.value = res.data
  })
}
</script>

<style lang="scss" scoped>
.user-list {
  .item {
    margin: 10px;
    padding: 10px;
    padding-top: 20px;
    background-color: #eef8ff;
    border-radius: 10px;
  }
}
.icon {
  height: 100%;
  width: 100%;
  // padding: 0 5px;
  // margin: 0 20px;
  display: flex;
  align-items: center;
  .close {
    flex: 1;
    cursor: pointer;
    font-size: 25px;
  }
}
</style>
